/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-09-05 18:19:07
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal } from 'antd';
import {
  ADD_DEPARTMENT,
  ADD_USER,
  CLEAR_SELECT_USER,
  DELETE_DEPARTMENT,
  DELETE_USER,
  EDIT_DEPARTMENT,
  SET_DEPARTMENT_LIST,
  SET_QUERY,
  SET_SELECT_DEPARTMENT,
  SET_SELECT_USER_ID,
  SET_USER_LIST,
  SHOW_USER_LIST_LOADING
} from '../constants';
import { OrgAndUserReducer } from '../reducers/OrgAndUserReducer';
import { addDepartment, deleteDepartment, editDepartment } from '@/api/department';
import { deleteUser, fetchUserListByPage, saveUser } from '@/api/user';
import { formatDate } from '@/utils';
import { appState } from '@/store/mobx';

const initialState = {
  // 当前选中的项目
  selectDepartment: {},
  selectUserIds: [],

  departmentList: [],
  departmentTree: [],
  // 用户列表相关
  userListLoading: false,
  userList: [],
  userQuery: {},
  userTotal: 0,

  // -------- 字典 --------
  // 密级
  securityList: [
    { id: 0, name: '不设置' },
    { id: 1, name: '公开' },
    { id: 2, name: '秘密' },
    { id: 3, name: '机密' },
    { id: 4, name: '绝密' }
  ],

  // 用户类型 - 只展示
  userTypeList: [
    { id: 0, name: '普通用户' },
    { id: 1, name: '部门资料员' },
    { id: 2, name: '部门领导' },
    { id: 3, name: '档案员' },
    { id: 4, name: '单位领导' }
  ],

  // 账号状态
  accountStateList: [
    { id: 0, name: '有效' },
    { id: 1, name: '无效' }
  ]
};

const OrgAndUserContext = createContext();

const OrgAndUserContextProvider = (props) => {
  const [state, dispatch] = useReducer(OrgAndUserReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的部门
     */
    setSelectDepartment(data) {
      dispatch({ type: SET_SELECT_DEPARTMENT, data });
      dispatch({ type: CLEAR_SELECT_USER });
    },

    /**
     * @description: 设置部门列表
     */
    setDepartmentList(data) {
      dispatch({ type: SET_DEPARTMENT_LIST, data });
    },

    /**
     * @description: 增加档案类型
     * @param {*} data 档案类型Obj
     */
    addDepartmentFunc(data) {
      return new Promise((resolve, reject) => {
        data.unitId = appState.unitId;
        addDepartment(data)
          .then((res) => {
            const data = res.data;
            dispatch({ type: ADD_DEPARTMENT, data });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 增加档案类型
     * @param {*} params 档案类型Obj
     */
    editDepartmentFunc(params) {
      return new Promise((resolve, reject) => {
        editDepartment(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_DEPARTMENT, data, id: data.id });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 增加档案类型
     * @param {Key} id 档案类型Obj
     */
    deleteDepartmentFunc(id) {
      Modal.confirm({
        title: '删除',
        content: '确认删除该部门？',
        onOk() {
          deleteDepartment(id).then((res) => {
            const ids = res.data;
            dispatch({ type: DELETE_DEPARTMENT, ids });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 设置排序列表请求条件
     * @param {{key: string, value: any}[]} info 修改的请求内容
     */
    setListQuery(info) {
      dispatch({ type: SET_QUERY, info });
    },

    /**
     * @description: 获取部门用户列表
     * @param {Object} data
     */
    getUserList(data) {
      dispatch({ type: SHOW_USER_LIST_LOADING });
      fetchUserListByPage(data).then((res) => {
        const { data } = res;
        dispatch({ type: SET_USER_LIST, data });
      });
    },

    /**
     * @description: 清空用户列表
     */
    clearUserList() {
      dispatch({ type: SET_USER_LIST, data: { results: [], total: 0 } });
    },

    /**
     * @description: 增加用户
     * @param {*} data 用户Obj
     * @param {'add'|'edit'} saveType 编辑标识符
     */
    addUserFunc(data, saveType = 'add') {
      data.user.pwdUpdateTime = formatDate();
      data.user.operator = 0;
      data.user.departmentId = state.selectDepartment.id;
      console.log(data);
      return new Promise((resolve, reject) => {
        saveUser({ ...data, roleIdList: data.user?.roleList || [] })
          .then((res) => {
            const { data } = res;
            data.user.roleList = data.roleIdList;
            dispatch({ type: ADD_USER, data, saveType });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 删除用户
     * @param {number|number[]} id 需要删除的用户id
     * @param {string} content 弹窗提示文案
     * @return {*}
     */
    deleteUserFunc(id, content = '确认删除选中的用户？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          const ids = Array.isArray(id) ? id.join(',') : id;
          deleteUser(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_USER, ids: data, srtIds: res.data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    changeSelectUserId(way, id) {
      dispatch({ type: SET_SELECT_USER_ID, way, id });
    }
  };

  const filters = {
    userTypeFilter(id) {
      return state.userTypeList.find((item) => item.id === id)?.name || '-';
    },
    userStateFilter(id) {
      return state.accountStateList.find((item) => item.id === id)?.name || '-';
    }
  };

  // watch listQuery来加载排序列表
  useEffect(() => {
    if (state.userQuery && JSON.stringify(state.userQuery) !== '{}') {
      actions.getUserList(state.userQuery);
    }
  }, [state.userQuery]);

  return (
    <OrgAndUserContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </OrgAndUserContext.Provider>
  );
};

export const useOrgAndUserContext = () => {
  return useContext(OrgAndUserContext);
};

export { OrgAndUserContext, OrgAndUserContextProvider };
